package com.yige.web.interceptor

import com.mongodb.DBObject
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.ModelAndView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by sunhao on 2015/9/17 0017.
 */

class CheckLoginInterceptor implements HandlerInterceptor{


    //执行Controller方法前调用
    @Override
    boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 获取session中的登录信息
        DBObject user = (DBObject)httpServletRequest.getSession().getAttribute("user")
        if(user == null){
            //用户没有登录，不能继续访问
            httpServletResponse.sendRedirect(
                    httpServletRequest.getContextPath() + "/jsp/sessionOut.jsp"
            )
            return false
        }else{
            //用户已经登陆
            List<String> list = (List<String>)httpServletRequest.getSession().getAttribute("auth")
            if(list.contains(httpServletRequest.getRequestURI())){
                //用户拥有权限
                return true
            }else {
                httpServletResponse.sendRedirect(
                        httpServletRequest.getContextPath() + "/jsp/error/noAuthority.jsp"
                )
                return false
            }
        }

    }

    //执行完Controller方法后调用
    @Override
    void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //请求结束时调用
    @Override
    void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }



}

